package com.chuangke.lowcode.component.save;

import com.baomidou.mybatisplus.extension.service.IService;
import com.chuangke.common.utils.SpringContextUtil;
import com.chuangke.lowcode.LowCodeContext;
import com.chuangke.lowcode.component.ProgressComponent;
import com.chuangke.lowcode.model.EntityModel;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Component
@Transactional(rollbackFor = Throwable.class)
public class SaveOrUpdateComponent implements ProgressComponent {

    public void process(LowCodeContext modelContext) {
        saveOrUpdate(Collections.singletonList(modelContext.getEntityModel()), modelContext.getModelDatas());
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private void saveOrUpdate(List<EntityModel> models, Map<String, List> datas) {
        for (EntityModel model : models) {
            IService service = (IService) SpringContextUtil.getBean(model.getServiceBeanName());
            service.saveOrUpdateBatch(datas.get(model.getId()));
            if (!CollectionUtils.isEmpty(model.getChildren())) {
                saveOrUpdate(model.getChildren(), datas);
            }
        }
    }

}
